#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django import template
from django.utils.safestring import mark_safe
register = template.Library()

from webadmin.views_dir.mongo_oper import get_db_obj
from bson.objectid import ObjectId


# 显示右侧栏目列表
@register.simple_tag
def show_column_list():
    columns_objs = get_db_obj().columns.find()

    result_html = ""
    for obj in columns_objs:
        result_html += """
            <li class="category-list-item"><a class="category-list-link" href="/{column_ename}/">{column_name} <span class="category-list-count">{column_article_num}</span></a></li>
        """.format(
            column_ename=obj["ename"],
            column_name=obj["name"],
            column_article_num=get_db_obj().articles.find({'column_id': obj["_id"], "show": 1}).count(),
        )

    return mark_safe(result_html)


# 显示右侧标签列表
@register.simple_tag
def show_tag_list():

    tags_objs = get_db_obj().tags.find()
    result_html = ""

    for obj in tags_objs:
        result_html += """
            <a href="/tags/{tag_name}/">{tag_name}</a>
        """.format(
            tag_name=obj["name"]
        )

    return mark_safe(result_html)


# 显示右侧最近文章列表
@register.simple_tag
def show_new_articles():
    articles_objs = get_db_obj().articles.find({"show": 1}, {"_id": 1, "title": 1, "column_id": 1}).limit(10)

    result_html = ""
    for obj in articles_objs:
        result_html += """
            <li class="post-list-item"><a class="post-list-link" href="/{column_ename}/{article_id}.html">{article_title}</a></li>
        """.format(
            column_ename=get_db_obj().columns.find_one({"_id": obj["column_id"]}, {"ename": 1})["ename"],
            article_id=obj["_id"],
            article_title=obj["title"],

        )

    return mark_safe(result_html)


